package com.asktgapp.user.fragment;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.ChoosePayWayFragment;
import com.asktgapp.dialog.ChooseStateFragment;
import com.asktgapp.dialog.ChooseTypeFragment;
import com.asktgapp.dialog.ConfirmPublishDialog;
import com.asktgapp.dialog.DatePickerFragment;
import com.asktgapp.dialog.JgLowDialog;
import com.asktgapp.dialog.PublishSuccessDialog;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.LawVO;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ChooseBrandActivity;
import com.asktgapp.user.activity.ChooseCityActivity;
import com.asktgapp.user.activity.MyPublishActivity;
import com.bigkoo.pickerview.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/31
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class PublishQiuzuFragment extends BaseFragment {
    @InjectView(R.id.tv_publish)
    TextView mPublish;
    @InjectView(R.id.tv_machine_type)
    TextView mChooseTypeTv;
    @InjectView(R.id.tv_brand)
    TextView mChooseBrandTv;
    @InjectView(R.id.tv_address)
    TextView mChooseAddress;
    @InjectView(R.id.tv_time_arived)
    TextView mArriveTimeTV;
    @InjectView(R.id.et_remark)
    EditText mRemarkET;
    @InjectView(R.id.et_name)
    EditText mLinkNameET;
    @InjectView(R.id.et_phone)
    EditText mLinkPhoneET;
    @InjectView(R.id.cb_law)
    CheckBox lawCb;
    @InjectView(R.id.et_price)
    EditText mPriceET;
    @InjectView(R.id.et_version)
    EditText mVersionET;
    @InjectView(R.id.et_weight)
    EditText mWeightET;
    @InjectView(R.id.tv_pay_way)
    TextView mPayWayTV;
    @InjectView(R.id.et_work_hour)
    EditText mWorkDayET;
    @InjectView(R.id.et_quantity)
    EditText mQuantityET;
    private String mCityId;
    private String mAreaId;
    private String mDate;
    private String mSelectedTypeId;
    private String mSelectedBrandId;
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();
    @InjectView(R.id.tv_law_fb)
    TextView mLawtv;
    private LawVO mLawVO;
    private EmojiFilter inputFilter;
    InputFilter[] inputFilters;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_qiuzu_publish, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        inputFilter=new EmojiFilter();
        inputFilters=new InputFilter[]{inputFilter};
        mRemarkET.setFilters(inputFilters);
        mLinkNameET.setFilters(inputFilters);
        mLinkPhoneET.setFilters(inputFilters);
        mPriceET.setFilters(inputFilters);
        mVersionET.setFilters(inputFilters);
        mWeightET.setFilters(inputFilters);
        mWorkDayET.setFilters(inputFilters);
        mQuantityET.setFilters(inputFilters);
        getBaseActivity().setBackNavigationIcon();
        mPublish.setOnClickListener(this);
        mArriveTimeTV.setOnClickListener(this);
        mChooseTypeTv.setOnClickListener(this);
        mChooseBrandTv.setOnClickListener(this);
        mPayWayTV.setOnClickListener(this);
        mChooseAddress.setOnClickListener(this);
        mLawtv.setOnClickListener(this);

    }

    @Override
    public void loadData() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });

        params.put("type", 8);
        Call<ApiResponseBody<LawVO>> call1 = apiservice.xieyiInfo(params);
        call1.enqueue(new Callback<ApiResponseBody<LawVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LawVO>> call, Response<ApiResponseBody<LawVO>> response) {
                if (response.isSuccessful()) {
                    mLawVO = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LawVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_publish:
                hideSoftKeyboard();
                if (Util.isEmpty(mPriceET.getText().toString().trim())) {
                    showTost("请输入价格", 1);
                    return;
                }
                if (Util.isEmpty(mSelectedTypeId) || Util.isEmpty(mChooseTypeTv.getText().toString().trim())) {
                    showTost("请选择设备类型", 1);
                    return;
                }
                if (Util.isEmpty(mSelectedBrandId) || Util.isEmpty(mChooseBrandTv.getText().toString().trim())) {
                    showTost("请选择品牌", 1);
                    return;
                }
                if (Util.isEmpty(mVersionET.getText().toString())) {
                    showTost("请输入型号", 1);
                    return;
                }
                if (mVersionET.getText().toString().length() > 20) {
                    showTost("型号长度不能超过20字,当前字数" + mVersionET.getText().toString().length(), 1);
                    return;
                }
                if (Util.isEmpty(mWeightET.getText().toString())) {
                    showTost("请输入吨位", 1);
                    return;
                }
                if (Util.isEmpty(mQuantityET.getText().toString())) {
                    showTost("请输入数量", 1);
                    return;
                }
                if (Util.isEmpty(mArriveTimeTV.getText().toString())) {
                    showTost("请选择最迟进场日期", 1);
                    return;
                }
                if (Util.isEmpty(mChooseAddress.getText().toString()) || Util.isEmpty(mAreaId)) {
                    showTost("请选择施工地点", 1);
                    return;
                }
                if (Util.isEmpty(mWorkDayET.getText().toString())) {
                    showTost("请输入工期", 1);
                    return;
                }
                if (Util.isEmpty(mPayWayTV.getText().toString())) {
                    showTost("请选择结款方式", 1);
                    return;
                }
                if (Util.isEmpty(mRemarkET.getText().toString()) || mRemarkET.getText().toString().length() < 10) {
                    showTost("请输入补充说明（最少十个字）", 1);
                    return;
                }
                if (mRemarkET.getText().toString().length() > 200) {
                    showTost("补充说明字数不能超过200字，当前字数：" + mRemarkET.getText().toString().length(), 1);
                    return;
                }
                if (Util.isEmpty(mLinkNameET.getText().toString())) {
                    showTost("请输入联系人姓名", 1);
                    return;
                }
                if (Util.isEmpty(mLinkPhoneET.getText().toString())) {
                    showTost("请输入联系电话", 1);
                    return;
                }
                if (!Util.isMobileNO(mLinkPhoneET.getText().toString())) {
                    showTost("请输入正确格式的手机号码", 1);
                    return;
                }
                if (!lawCb.isChecked()) {
                    showTost("您未勾选发布协议，如果您同意该协议，请勾选", 1);
                    return;
                }
                ConfirmPublishDialog confirmPublishDialog = new ConfirmPublishDialog(new ConfirmPublishDialog.onResultCallBack() {
                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onSure() {
                        requestNetAndPublish();

                    }
                }, "确认发布当前求租信息？");
                confirmPublishDialog.show(getFragmentManager(), "ConfirmPublishDialog");
                break;

            case R.id.tv_machine_type:
                ChooseTypeFragment chooseTypeFragment = new ChooseTypeFragment(new ChooseTypeFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mChooseTypeTv.setText(s[1]);
                        mSelectedTypeId = s[0];
//                        getBrandLlist();
                    }
                }, mTypeList, "请选择设备类型");
                chooseTypeFragment.show(getFragmentManager(), "ChooseTypeFragment");
                break;


            case R.id.tv_brand:
                if (Util.isEmpty(mChooseTypeTv.getText().toString().trim())) {
                    showTost("请先选择设备类型", 1);
                    return;
                }

//                ChooseBrandDialogFragment chooseBrandFragment = new ChooseBrandDialogFragment(new ChooseBrandDialogFragment.Callback() {
//                    @Override
//                    public void onSelect(String... s) {
//                        mSelectedBrandId = s[0];
//                        mChooseBrandTv.setText(s[1]);
//                    }
//                }, mBrandList, "请选择品牌");
//                chooseBrandFragment.show(getFragmentManager(), "ChooseTypeFragment");
                Intent intent = new Intent(getActivity(), ChooseBrandActivity.class);
                intent.putExtra("typeId", mSelectedTypeId);
                startActivityForResult(intent, 200);
                break;

            case R.id.tv_address:
                Intent address = new Intent(getActivity(), ChooseCityActivity.class);
                startActivityForResult(address, 300);

                break;
            case R.id.tv_time_arived:

                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        if (!Utils.isFutureDate(Util.DateToStr(date2, "yyyy-MM-dd"))) {
                            showTost("不能选择过去的时间！", 1);
                        } else
                            mArriveTimeTV.setText(Util.DateToStr(date2, "yyyy-MM-dd"));

                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(20)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(JGColor.APP_BASIC_BLUE)//确定按钮文字颜色
                        .setCancelColor(JGColor.APP_BASIC_BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();

//                DatePickerFragment picker = new DatePickerFragment(new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//
//                        mDate = Utils.getDateString(year, month, dayOfMonth);
//                        if (!Utils.isFutureDate(mDate)) {
//                            showTost("不能选择过去的时间！", 1);
//                        } else
//                            mArriveTimeTV.setText(mDate);
//                    }
//                });
//                picker.show(getFragmentManager(), "DatePickerFragment");

                break;
            case R.id.tv_pay_way:
                List<String> list = new ArrayList<>();
                list.add("现款");
                list.add("工程结束");
                list.add("协商付款");
                ChoosePayWayFragment chooseFragment = new ChoosePayWayFragment(new ChoosePayWayFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mPayWayTV.setText(s[0]);
                    }
                }, list, "");
                chooseFragment.show(getFragmentManager(), "ChooseStateFragment");
                break;

            case R.id.tv_law_fb:
                JgLowDialog jgLowDialog1 = new JgLowDialog("发布协议", mLawVO.getContent());
                jgLowDialog1.show(getFragmentManager(), "JgLowDialog1");
                break;
        }

    }

    private void requestNetAndPublish() {

        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("price", mPriceET.getText().toString().trim());
        params.put("typeId", mSelectedTypeId);
        params.put("brandId", mSelectedBrandId);
        params.put("model", mVersionET.getText().toString().trim());
        params.put("tonnage", mWeightET.getText().toString().trim());
        params.put("cityId", mCityId);
        params.put("areaId", mAreaId);
        params.put("endTime", mArriveTimeTV.getText().toString().trim());
        params.put("timeLimit", mWorkDayET.getText().toString().trim());
        params.put("info", mRemarkET.getText().toString().trim());
        params.put("linkName", mLinkNameET.getText().toString().trim());
        params.put("linkPhone", mLinkPhoneET.getText().toString().trim());
        params.put("number", mQuantityET.getText().toString().trim());
        if (mPayWayTV.getText().toString().trim().equals("现款")) {
            params.put("payType", "0");
        } else if (mPayWayTV.getText().toString().trim().equals("工程结束")) {
            params.put("payType", "0");
        } else if (mPayWayTV.getText().toString().trim().equals("协商付款")) {
            params.put("payType", "0");
        }
        showProgress(getClass().getSimpleName());
        Apiservice apiservice = ApiUtil.getInstance().create();
        Call<ApiResponseBody> call = apiservice.subQiuZu(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
//                    PublishSuccessDialog publishSuccessDialog = new PublishSuccessDialog();
//                    publishSuccessDialog.setOnDismiss(new PublishSuccessDialog.onDissmissListener() {
//                        @Override
//                        public void onDismiss() {
                    showTost("发布成功", 0);
                    startActivity(new Intent(getActivity(), MyPublishActivity.class));
                    getActivity().finish();
//                        }
//                    });
//                    publishSuccessDialog.show(getFragmentManager(), "PublishSuccessDialog");
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200) {
                mChooseBrandTv.setText(data.getStringExtra("brand"));
                mSelectedBrandId = data.getStringExtra("brandId");
            }
            if (requestCode == 300) {
                mAreaId = data.getStringExtra("areaId");
                mCityId = data.getStringExtra("cityId");
                mChooseAddress.setText(data.getStringExtra("area") + "  " + data.getStringExtra("city"));
            }
        }
    }
}
